package com.lsh.service.impl;

import com.lsh.model.ESArticle;
import com.lsh.repository.ArticleRepository;
import com.lsh.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author ：LiuShihao
 * @date ：Created in 2020/10/30 10:16 上午
 * @desc ：
 */
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    ArticleRepository repository;

    /**
     * 向ES中添加数据
     * @param article
     */
    @Override
    public void save(ESArticle article){
        repository.save(article);
    }

    /**
     * 查询ES中的所有数据
     * @return
     */
    @Override
    public List<ESArticle> findAll() {
        Iterable<ESArticle> all = repository.findAll();
        List<ESArticle> articles = new ArrayList<>();
        Iterator<ESArticle> iterator = all.iterator();
        while (iterator.hasNext()){
            ESArticle article = iterator.next();
            articles.add(article);
        }
        return articles;
    }

    /**
     * 根据条件查询ES中的数据 分页
     * @param key
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<ESArticle> findByKey(String key, int page, int size) {
        Pageable pageable = PageRequest.of(page-1, size);
        if (key == null){
            Page<ESArticle> all = repository.findAll(pageable);
            return all;
        }
        return repository.findByTitleOrContentLike(key, key, pageable);
    }

}
